package com.tencent.sr.iris.basic.saas.service.model.activity;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.sr.iris.basic.saas.common.enums.MultiTaskStatusEnum;
import com.tencent.sr.iris.basic.saas.common.enums.YesOrNoEnum;
import com.tencent.sr.iris.basic.saas.common.utils.CommonUtils;
import com.tencent.sr.iris.basic.saas.interfaces.response.activity.ActivityTaskPageResponse;
import com.tencent.sr.iris.basic.saas.interfaces.response.activity.SentAwardInfo;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Data
@ApiModel(value = "活动明细导出信息")
@Slf4j
@ColumnWidth(15)
public class InviteActivityTaskBaseExportInfo extends BaseActivityTaskExportInfo {

    @ExcelProperty(value = "贡献周期", index = 17)
    protected String currentTaskTime;

    @ExcelProperty(value = "有效分享数", index = 18)
    protected Integer shareCount;

    @ExcelProperty(value = "预估收益", index = 19)
    protected Double estimateCommission;

    @ExcelProperty(value = "实际收益", index = 20)
    protected Double commission;

    @ExcelProperty(value = "预估奖励佣金", index = 21)
    private Double rewardIncomeAmt;

    @ExcelProperty(value = "实际奖励佣金", index = 22)
    private Double actualSalesRewardIncomeAmtAll;

    @ExcelProperty(value = "任务状态", index = 23)
    protected String userTaskStatus;

    @ExcelProperty(value = "推送发奖时间", index = 24)
    protected String awardSendTime;

    @ExcelProperty(value = "GMV", index = 25)
    protected Double gmv;

    @ExcelProperty(value = "首单实付金额", index = 26)
    protected Double firstOrderAmount;

    @ExcelProperty(value = "首单分销单号", index = 27)
    protected String plainOrderId;

    @ExcelProperty(value = "奖励金金额", index = 28)
    protected String awardAmount;

    @ExcelProperty(value = "预估奖励金金额", index = 29)
    protected Double estimateAwardAmount;

    @Override
    public void readFromSearchResponseData(ActivityTaskPageResponse response, Map<Long, String> areaMap) {
        super.readFromSearchResponseData(response, areaMap);

        if (Objects.equals(response.getIsParticipated(), YesOrNoEnum.YES.name())) {
            //已参加任务
            String statusText = Optional.ofNullable(MultiTaskStatusEnum.getByCode(response.getCommonTaskStatus()))
                    .map(i -> i == MultiTaskStatusEnum.UNFINISHED ? i.getDesc()
                            : new StringBuilder(i.getDesc()).append("（")
                            .append(response.getStage()).append("阶）").toString()).orElse(StrUtil.EMPTY);
            this.setUserTaskStatus(statusText);

            String currentTaskStartTime = Optional.ofNullable(response.getCurrentTaskStartTime())
                    .map(i -> DateUtil.formatDateTime(DateUtil.date(i))).orElse(StrUtil.UNDERLINE);
            String currentTaskEndTime = Optional.ofNullable(response.getCurrentTaskEndTime())
                    .map(i -> DateUtil.formatDateTime(DateUtil.date(i))).orElse(StrUtil.UNDERLINE);
            this.setCurrentTaskTime(currentTaskStartTime + "至" + currentTaskEndTime);
        } else {
            this.setCurrentTaskTime(StrUtil.DASHED);
            this.setUserTaskStatus(StrUtil.DASHED);
        }

        this.setShareCount(response.getShareCount());

        Double rewardIncomeAmt = CommonUtils.integerToDouble(response.getRewardIncomeAmt());
        this.setRewardIncomeAmt(rewardIncomeAmt);

        Double actualSalesRewardIncomeAmtAll = CommonUtils.integerToDouble(response.getActualSalesRewardIncomeAmtAll());
        this.setActualSalesRewardIncomeAmtAll(actualSalesRewardIncomeAmtAll);

        Double estimateCommission = CommonUtils.integerToDouble(response.getEstimateCommission());
        this.setEstimateCommission(estimateCommission);

        Double commission = CommonUtils.integerToDouble(response.getCommission());
        this.setCommission(commission);

        List<SentAwardInfo> sentAwardInfoList = response.getSentAwardInfoList();
        String amountText = sentAwardInfoList.stream()
                .map(i -> String.format("%s阶：￥ %s", i.getStage(),
                        CommonUtils.integerToDouble(i.getAwardAmount()))).collect(Collectors.joining("\n"));
        String sendTimeText = sentAwardInfoList.stream()
                .map(i -> String.format("%s阶：%s", i.getStage(), DateUtil.formatDateTime(DateUtil.date(i.getAwardSendTime()))))
                .collect(Collectors.joining("\n"));
        this.setAwardSendTime(sendTimeText);
        this.setAwardAmount(amountText);

        Double gmv = CommonUtils.integerToDouble(response.getGmv());
        this.setGmv(gmv);

        // 设置首单实付金额与分销单号
        String extInfo = response.getExtInfo();
        if (StrUtil.isNotBlank(extInfo)) {
            JSONObject extInfoJson = Optional.ofNullable(JSON.parseObject(extInfo))
                    .orElseGet(JSONObject::new);
            JSONObject firstOrder = extInfoJson.getJSONObject("firstOrder");
            if (Objects.nonNull(firstOrder)) {
                Integer couponPrice = Optional.ofNullable(firstOrder.getInteger("couponPrice")).orElse(0);
                Integer paymentAmount = Optional.ofNullable(firstOrder.getInteger("paymentAmount")).orElse(0);
                // 实付金额 = paymentAmount - 优惠券金额
                int paymentAmt = paymentAmount - couponPrice;
                this.setFirstOrderAmount(CommonUtils.integerToDouble(Math.max(paymentAmt, 0)));
                // 分销单号
                this.setPlainOrderId((String) firstOrder.get("plainOrderId"));
            }
        }

        Double estimateAwardAmount = CommonUtils.integerToDouble(response.getEstimateAwardAmount());
        this.setEstimateAwardAmount(estimateAwardAmount);
    }

}
